<?php

namespace Beerus\Modules\DesignerService\Actions;

use Encore\Admin\Actions\Action;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Doraemon\model\DesignerService\ContractKeyword as mContractKeyword;

class CreateKeywords extends Action
{
	public $name = '设置审核关键词';

    protected $selector = '.import-post';

	public function handle(Request $request) {
        $aExistKeywords = mContractKeyword::getAllNormalKeywords();
	    $sKeywords = $request->get('keywords');
        $aKeywords = [];
	    if (!empty($sKeywords)) {
            $aKeywords = explode("\r\n", $sKeywords);
        }
	    $aNewKeywords = [];
	    foreach ($aKeywords as $sKeyword) {
            if (!empty($sKeyword) && !in_array($sKeyword, $aExistKeywords)) {
                $aNewKeywords[] = [
                    'name' => $sKeyword,
                    'add_time' => time()
                ];
            }
        }
	    $aRemoveKeywords = array_diff($aExistKeywords, $aKeywords);
	    if (!empty($aNewKeywords)) {
            mContractKeyword::batchAddData($aNewKeywords);
        }
	    if (!empty($aRemoveKeywords)) {
            mContractKeyword::delete(['name' => $aRemoveKeywords]);
        }
        return $this->response()->success('提交成功.')->refresh();
	}

    public function form()
    {
        $aKeywords = mContractKeyword::getAllNormalKeywords();
        $sKeywords = $aKeywords ? implode("\r\n", $aKeywords) : '';
        $this->textarea('keywords', '关键词')
            ->placeholder('关键词以回车分割')
            ->default($sKeywords);
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-post"><i class="fa"></i>设置审核关键词</a>
HTML;
    }
}
